import React, { useRef, FC, forwardRef, useImperativeHandle, useState, useEffect } from 'react'
import { withRouter } from 'react-router-dom'
import TableDefined from '@/components/common/tableDefined'
import CleanFusion from '@/api/cleanFusion'
import { modalLayoutLg } from '@/config/layout'
import './index.less'
import { Button, Input, Select, Modal, DatePicker, Form, Row, Col, TimePicker, Steps, Table, Checkbox, Spin, message } from 'antd';
import MyDefineSelect from '@/components/common/myDefineSelect'
import $axios from '@/utils/axios';
import { fn } from 'moment'
import Dynamic from '@/api/dynamic'
import moment from 'moment';
import DefineSelect from '@/components/common/tableDefinedEdit/DefineSelect.tsx'
import DefineSelectComp from '@/components/common/tableDefinedEdit/DefineSelectComp.tsx'
import { ArrowRightOutlined, PlusCircleOutlined, PlusOutlined, RightCircleOutlined, RightOutlined } from '@ant-design/icons'
const { Option } = Select;
const { RangePicker } = DatePicker;

const CleanRole: FC = () => {
  const tableRef: RefType = useRef()
  const AddMComRef: RefType = useRef()
  const LogMComRef: RefType = useRef()
  const [schTypeObj, setschTypeObj] = useState({ 1: '定时', 2: '单次' });
  const [scripTypeObj, setscripTypeObj] = useState({});
  const [searchConfigList, setsearchConfigList] = useState([]);
  const [orderBy, setOrderBy] = useState('');
  const [loading, setLoading] = useState(true);
  const [connector, setconnector] = useState({});
  useEffect(() => {
    Dynamic.getDynamicQuery({
      apiID: 'DICT_0001_01',
      apiParam: {
        "dict_key": "data_gov_script"
      }
    }).then((res) => {
      let data = res?.data?.data || [];
      console.log('脚本类型')
      console.log(data);

      let obj = {};
      data.map((e) => {
        obj[e.value] = e.label
      })
      console.log(obj);
      setscripTypeObj(obj);
    })
    getSearchConfig();
  }, [])

  const getSearchConfig = () => {
    Dynamic.getDynamicQuery({
      apiID: 'DMT_MNG_01',
      apiParam: {
        api_id: 'DMT_A002'
      }
    }).then((res) => {
      let data = res.data;
      let apiParamStr = data.data['0']['api_param'] ? data.data['0']['api_param'] : '';
      let apiParam = data.data['0']['api_param'] ? JSON.parse(data.data['0']['api_param']) : {};
      let { paramList = [] } = apiParam;
      paramList.map((e, i) => {

        switch (e.name) {
          case "where"://查询条件
            let element = e.element || [];
            let searchConfigListNew = [];

            let connectorNew = {};

            element.map((el, il) => {
              connectorNew[el.feild] = el['connector'];
              let ele = {
                "key": el.feild,
                // "slot": <Input placeholder={"请输入"+el.label} allowClear />,
                "rules": [],
                // "initialValue": '',
                "label": el.label,
              }
              switch (el.type) {
                case 'text':
                  ele['slot'] = <Input placeholder={"请输入" + el.label} allowClear />;
                  break;
                case 'checkbox':
                  ele['slot'] = <Checkbox.Group style={{ maxWidth: window.innerWidth / 2 - 100 + 'px' }}>
                    {
                      el.option.map((ek, ik) => {
                        return <Checkbox defaultChecked={ek.checked} key={ik} value={ek.value}>{ek.label}</Checkbox>
                      })
                    }
                  </Checkbox.Group>
                  break;
                case 'select':
                  if (el?.option_url) {
                    if (el.mode == "multiple") {
                      ele['slot'] = <DefineSelect mode='multiple' {...el.option_url} />
                      ele['initialValue'] = [];
                    } else {
                      ele['slot'] = <DefineSelect {...el.option_url} />
                    }

                  } else {
                    if (el.mode == "multiple") {
                      ele['slot'] = <Select allowClear mode='multiple' placeholder={'请选择' + el.label} style={{ maxWidth: window.innerWidth / 2 - 100 + 'px', minWidth: '120px' }}>
                        {
                          el.option.map((ek, ik) => {
                            return <Option defaultChecked={ek.checked} key={ik} value={ek.value}>{ek.label}</Option>
                          })
                        }
                      </Select>
                    } else {
                      ele['slot'] = <Select allowClear placeholder={'请选择' + el.label} style={{ maxWidth: window.innerWidth / 2 - 100 + 'px', minWidth: '120px' }}>
                        {
                          el.option.map((ek, ik) => {
                            return <Option defaultChecked={ek.checked} key={ik} value={ek.value}>{ek.label}</Option>
                          })
                        }
                      </Select>
                    }
                  }


                default:
                  break;
              }
              searchConfigListNew.push(ele)
              setconnector(connectorNew)
            })
            setsearchConfigList(searchConfigListNew);

            break;
          case 'orderBy'://排序
            setOrderBy(e.value);
            break;
          case 'paging'://分页
            break;
        }
      })

      setLoading(false);
    })

  }
  const columns = [

    {
      title: '操作',
      dataIndex: 'scan',
      key: 'scan',
      width: '280px',
      fixed: 'right',
      render(txt, record, index) {
        return <div>
          <Button className="btn" onClick={() => edit(record.task_id)} size="small">
            编辑
          </Button>
          <Button className="btn" style={{ marginLeft: '15px' }} onClick={() => test(record.task_id)} size="small">
            测试
          </Button>
          <Button className="btn" style={{ marginLeft: '15px' }} onClick={() => publicMethod(record.task_id)} size="small">
            发布
          </Button>
          <Button className="btn" style={{ marginLeft: '15px' }} onClick={() => del(record.task_id)} size="small">
            删除
          </Button>
        </div>
      }
    },
  ]
  // 新增按钮
  const AddBtn = () => (
    <Button className="fr" onClick={add} type="primary">
      新增
    </Button>
  )
  const BatchDelBtn = () => (

    <Button style={{ marginRight: '15px' }} className="fr" onClick={del}>
      删除
    </Button>
  )
  // 添加
  const add = () => {
    AddMComRef.current.init()
  }
  // 添加
  const edit = (id) => {
    AddMComRef.current.init(id);
  }
  // 删除
  const del = (id: any) => {
    Modal.confirm({
      title: '确认删除？',

      onOk() {
        // Role.roleDel({
        //   roleid:record.roleid,
        //   isFormData:true
        // }).then(()=>{
        //   tableRef.current.update();
        // })
        Dynamic.DynamicExecute({
          apiID: 'DMT_A002_03',
          apiParam: {
            PRIMARY_ID: id
          }
        }).then((res) => {
          tableRef.current.update();
        })
      },
      onCancel() {
        console.log('Cancel');
      },
    });
  }
  //发布
  const publicMethod = (id: any) => {
    Modal.confirm({
      title: '确认发布？',

      onOk() {
        // Role.roleDel({
        //   roleid:record.roleid,
        //   isFormData:true
        // }).then(()=>{
        //   tableRef.current.update();
        // })
        Dynamic.DynamicExecute({
          apiID: 'DMT_A002_05',
          apiParam: {
            PRIMARY_ID: id
          }
        }).then((res) => {
          message.success('发布成功');
          tableRef.current.update();
        })
      },
      onCancel() {
        console.log('Cancel');
      },
    });
  }
  // 测试
  const test = (id: any) => {
    Dynamic.DynamicExecute({
      apiID: 'DMT_A002_06',
      apiParam: {
        PRIMARY_ID: id
      }
    }).then((res) => {
      console.log(res?.data?.logID);
      LogMComRef.current.init(res?.data?.logID);
      tableRef.current.update();
    })
  }
  return (
    <>
      <div>
        <AddBtn />
        {/* <BatchDelBtn /> */}
      </div>

      {
        !loading && <TableDefined
          apiFun={Dynamic.getDynamicQuery}
          columns={columns}
          ref={tableRef}
          searchConfigList={searchConfigList}
          extraProps={{ apiID: 'DMT_A002', apiParam: { 'orderBy': orderBy } }}
          // onSelectRow={(val) => {
          //   console.log(val);
          // }}
          rowKey='id'
          beforeSearch={(val: any) => {
            // eslint-disable-next-line no-param-reassign
            console.log(val);
            val.where = [];
            for (let i in val) {
              if (i != 'where' && val[i] && val[i]['length'] > 0) {
                val.where.push({ "feild": i, "connector": connector[i], "value": val[i] })
              }
            }
            for (let i in val) {
              if (i != 'where') {
                delete val[i];
              }
            }
            // eslint-disable-next-line no-param-reassign
            return {}
          }}
        />
      }

      <AddMCom ref={AddMComRef} callback={() => {
        tableRef.current.update();
      }} />
      <LogMCom ref={LogMComRef} callback={() => {
        tableRef.current.update();
      }} />
    </>
  )
}
export default withRouter(CleanRole)

const AddM = (props, refs) => {

  const [form] = Form.useForm()
  // const [fileList,setfileList] = useState([]);
  const [measureClassData, setmeasureClassData] = useState([]);
  const { setFieldsValue, resetFields } = form
  const [id, setid] = useState('')
  const [isModalVisible, setIsModalVisible] = useState(false);
  const sch_typeValue = Form.useWatch('sch_type', form);
  const schemaValue = Form.useWatch('schema', form);
  const scriptYypeValue = Form.useWatch('script_type', form);
  const [isSetFields, setisSetFields] = useState(false);
  const tableNameValue = Form.useWatch('table_name', form);
  const [stepsArr, setstepsArr] = useState([{}])
  const [stepsCurrent, setstepsCurrent] = useState(0)
  const [databaselist, setdatabaselist] = useState([]);
  const [fieldlist, setfieldlist] = useState([]);
  const [changeFlag, setchangeFlag] = useState(false);
  const [isloading, setloading] = useState(false);
  //显示弹窗
  const showModal = () => {
    setIsModalVisible(true);
  };

  //确定
  const handleOk = () => {
    form.validateFields().then((vals) => {
      const Obj = form.getFieldsValue()
      try {
        Obj['db_source'] = Obj['schema']
        console.log(Obj);
        let newstepsArr = stepsArr.concat([]);
        newstepsArr.map((e, i) => {
          let fields = e?.fields || [];
          let checked = e?.checked || [];
          let selectIndexs = [];
          fields.map((e, i) => {
            if (checked.indexOf(e.column_name) != -1) {
              selectIndexs.push(i);
            }
          })


          let DATA = e['SUB_DATA'][0]['DATA'];
          let newData = [];
          selectIndexs.map((e, i) => {
            DATA[e]['step_sno'] = i + 1;
            newData.push(DATA[e]);
          })
          newstepsArr[i]['SUB_DATA'][0]['DATA'] = newData;
          // delete newstepsArr[i]['fields']
          // delete newstepsArr[i]['checked']

        })
      } catch (error) {
        console.log(error);
      }
      //demo_nrg_ods.ods_coal_org code

      let params = {
        "FORM_DATA": {
          "API_ID": id ? "DMT_A002_02" : "DMT_A002_01",
          "DATA": [
            {
              ...Obj,
              ...{
                SUB_DATA: [{
                  "API_ID": "DMT_A003_01",
                  DATA: stepsArr
                }]
              }
            }
          ]
        }
      }
      if (id) {
        params['FORM_DATA']['DATA'][0]['SUB_DATA'].unshift({
          "API_ID": "DMT_A003_04"
        })
        params['FORM_DATA']['DATA'][0]['PRIMARY_ID'] = id;
      }
      console.log('params');
      console.log(params);

      Dynamic.FormSubmit(params).then((res) => {
        handleCancel();
      })
    }).catch(info => {

    })
  };
  //取消
  const handleCancel = () => {
    setIsModalVisible(false);
    resetFields();
    setid('');
    props.callback && props.callback();
  };
  useImperativeHandle(refs, () => ({
    init: (id) => {
      if (id) {
        setid(id)
        getDetail(id);
      } else {
        resetFields();
        setid('');
        setFieldsValue({
          sch_type: '1'
        })
      }
      showModal();
      // setfileList([]);
    }
  }))
  useEffect(() => {
    // console.log('stepsArr改变' + new Date().getTime())
    // console.log(stepsArr)
  }, [stepsArr])
  useEffect(() => {
    let schemaValueNew = schemaValue;

    if (!isSetFields) {
      // console.log('setstepsArr 位置1')
      setstepsArr([{
        // "step_sno": 2,
        "db_schema": schemaValue,//数据源
        "table_name": "",//原表
        "cmd_type": "",//???
        "step_script": "",//脚本
        "comb_rls": "",//关联关系
        "filte_condition": "",//过滤条件
        "SUB_DATA": [{
          "API_ID": "DMT_A004_01",
          "DATA": [{
            "tgt_column": "",
            "data_type": "",
            "db_source": "",
            "db_schema": "",
            "table_name": "",
            "src_column": "",
            "rule_id": "",
            "rule_param": "",
            "checked": []
          }]
        }]
      }]);

      setstepsCurrent(-1);
      setTimeout(() => {
        setstepsCurrent(0);
      }, 500);
    }

  }, [schemaValue])
  useEffect(() => {
    Dynamic.getDynamicQuery({
      apiID: 'DMT_0002_01',
    }).then((res) => {

      let data = res?.data?.data || []
      setdatabaselist(data);
    })
  }, [1])
  const getDetail = (id) => {
    setloading(true);
    Dynamic.FormGet({
      "FORM_DATA": {
        "API_ID": "DMT_A002_04",
        "PRIMARY_ID": id,
        "SUB_DATA": [
          {
            "API_ID": "DMT_A003_05",
            "PARENT_COLUMN": "task_id",
            "PRIMARY_COLUMN": "step_id",
            "SUB_DATA_KEY": "STEP_LIST",
            "SUB_DATA": [
              {
                "API_ID": "DMT_A004_05",
                "PARENT_COLUMN": "step_id",
                "SUB_DATA_KEY": "COLMAP_LIST"
              }
            ]
          }
        ]
      }
    }).then(async (res) => {
      setisSetFields(true);
      let data = res['data'];
      await setFieldsValue({
        ...data,
        ...{
          schema: data.db_source
        }
      })
      let STEP_LIST = res?.data?.STEP_LIST || [];

      STEP_LIST.map((e, i) => {

        // let COLMAP_LIST = e?.COLMAP_LIST||[];
        STEP_LIST[i]['SUB_DATA'] = [];
        STEP_LIST[i]['SUB_DATA'].push({
          "API_ID": "DMT_A004_01",
          "DATA": []
        })
      })
      // console.log(STEP_LIST);
      console.log('setstepsArr 位置2')
      // setstepsArr(STEP_LIST);
      // setstepsCurrent(-1);
      setTimeout(() => {

        STEP_LIST.map((e, i) => {
          Dynamic.getDynamicQuery({
            apiID: 'DMT_0003_02',
            'apiParam': {
              "table_name": e['table_name'],
              "schema": e['db_schema']
            }
          }).then((res) => {
            let COLMAP_LIST_OBJ = {};
            let COLMAP_LIST = e?.COLMAP_LIST || [];
            COLMAP_LIST.map((e, i) => {
              COLMAP_LIST_OBJ[e.tgt_column] = e;
            })
            let data = res?.data?.data || []
            // setfieldlist(data)
            console.log(stepsArr);
            let newstepsArr = STEP_LIST.concat([])
            newstepsArr[i]['fields'] = data;
            newstepsArr[i]['checked'] = Object.keys(COLMAP_LIST_OBJ);
            console.log('setstepsArr 位置3')
            console.log(newstepsArr)
            data.map((el, il) => {
              newstepsArr[i]['SUB_DATA'][0]['DATA'].push({
                "tgt_column": el["column_name"],
                "data_type": el['data_type'],
                "db_source": "",
                "db_schema": "",
                "table_name": "",
                "src_column": "",
                "rule_id": "",
                "rule_param": ""
              });
              newstepsArr[i]['SUB_DATA'][0]['DATA'][il] = {
                ...newstepsArr[i]['SUB_DATA'][0]['DATA'][il],
                ...COLMAP_LIST_OBJ[el['column_name']]
              }
            })
            setstepsArr(newstepsArr)
          })
        })
        setisSetFields(false);
        setloading(false);
      }, 1000);

      // tableRef.current.update();
    })

    // Dynamic.getDynamicQuery({
    //   apiID: 'DMT_A003_05',
    //   apiParam: {
    //     "PARENT_ID": id
    //   }
    // }).then((res) => {
    //   let data = res['data']['data'][0];
    //   // tableRef.current.update();
    // })
  }

  const columns = [
    {
      title: '序号',
      align: 'center',
      dataIndex: 'index',
      key: 'index',
      width: '80px',
      fixed: 'left',
      render: (text, record, index) => {
        return index + 1
      }
    },
    {
      title: '字段',
      dataIndex: 'column_name',
      key: 'column_name',
    },
    {
      title: '数据类型',
      dataIndex: 'data_type',
      key: 'data_type',
    },

    {
      title: '数据源',
      dataIndex: 'db_source',
      key: 'db_source',
      width: '160px',
      render(txt, record, index) {
        return <DefineSelectComp value={stepsArr?.[stepsCurrent]?.['SUB_DATA']?.[0]['DATA']?.[index]?.['db_schema']} onChange={(val) => {
          changeSUBDATAValue('db_schema', val, index);
          if(val==''){
            changeSUBDATAValue('table_name', '', index);
            changeSUBDATAValue('src_column', val, index);
          }
        }} style={{ minWidth: '150px' }}  {
          ...{
            "api_id": "DMT_0002_01",
            "key_label": "label",
            "key_value": "value",
          }
          } allowClear>
        </DefineSelectComp>
      },
    },
    {
      title: '原表',
      dataIndex: 'table_name',
      key: 'table_name',
      width: '160px',
      render(txt, record, index) {
        let schemad = stepsArr?.[stepsCurrent]?.['SUB_DATA']?.[0]['DATA']?.[index]?.['db_schema'];
        return schemad && <DefineSelectComp
          value={stepsArr?.[stepsCurrent]?.['SUB_DATA']?.[0]['DATA']?.[index]?.['table_name']} onChange={(val) => {
            changeSUBDATAValue('table_name', val, index);
            if(val==''){
              changeSUBDATAValue('src_column', val, index);
            }
          }}

          {
          ...{
            "api_id": "DMT_0003",
            "key_label": "tablename",
            "key_value": "tablename",
            "param": { "schema": schemad },
          }
          } />
      },
    },
    {
      title: '原字段',
      dataIndex: 'src_column',
      key: 'src_column',
      width: '130px',
      render(txt, record, index) {
        let schemad = stepsArr?.[stepsCurrent]?.['SUB_DATA']?.[0]['DATA']?.[index]?.['db_schema'];
        let table_named = stepsArr?.[stepsCurrent]?.['SUB_DATA']?.[0]['DATA']?.[index]?.['table_name'];
        return schemad && table_named && <DefineSelectComp
          value={stepsArr?.[stepsCurrent]?.['SUB_DATA']?.[0]['DATA']?.[index]?.['src_column']} onChange={(val) => {
            changeSUBDATAValue('src_column', val, index);
            setTimeout(() => {
              let newstepsArr = stepsArr.concat([])
              let db_schema = stepsArr?.[stepsCurrent]?.['SUB_DATA']?.[0]['DATA']?.[index]?.['db_schema']
              let table_name = stepsArr?.[stepsCurrent]?.['SUB_DATA']?.[0]['DATA']?.[index]?.['table_name']

              try {
                if (newstepsArr[stepsCurrent]['SUB_DATA'][0]['DATA'][index + 1]['src_column'] == '') {
                  newstepsArr[stepsCurrent]['SUB_DATA'][0]['DATA'][index + 1]['db_schema'] = db_schema;
                  newstepsArr[stepsCurrent]['SUB_DATA'][0]['DATA'][index + 1]['table_name'] = table_name;
                }

              } catch (error) {

              }
              console.log('setstepsArr 位置5')
              setstepsArr(newstepsArr)
            }, 200);

          }}

          {
          ...{
            "api_id": "DMT_0003_02",
            "key_label": "column_name",
            "key_value": "column_name",
            "param": {
              "table_name": table_named,
              "schema": schemad
            },
          }
          } />
      },
    },
    {
      title: '清洗规则',
      dataIndex: 'rule_id',
      key: 'rule_id',
      width: '140px',
      render(txt, record, index) {
        return <DefineSelectComp
          value={stepsArr?.[stepsCurrent]?.['SUB_DATA']?.[0]['DATA']?.[index]?.['rule_id']} onChange={(val) => {
            changeSUBDATAValue('rule_id', val, index);
          }}

          {
          ...{
            "api_id": "DMT_A001",
            "key_label": "rule_name",
            "key_value": "rule_id",
            "param": { "paging": { "pageNum": 1, "pageSize": 10 } },
          }
          } />
      },
    },
    {
      title: '清洗参数',
      dataIndex: 'rule_param',
      key: 'rule_param',
      render(txt, record, index) {
        return <Input value={stepsArr?.[stepsCurrent]?.['SUB_DATA']?.[0]['DATA']?.[index]?.['rule_param']} onChange={(e) => {
          changeSUBDATAValue('rule_param', e.target.value, index);
        }} />
      }
    },
  ]
  const changeValue = (name, value) => {
    let newstepsArr = stepsArr.concat([])
    newstepsArr[stepsCurrent][name] = value;
    console.log('setstepsArr 位置4')
    console.log(newstepsArr);
    setstepsArr(newstepsArr)
  }
  const changeComb_rlsValue = (name, value, index) => {
    let newcomb_rls = stepsArr[stepsCurrent]['comb_rls'] == '' ? [] : JSON.parse(stepsArr[stepsCurrent]['comb_rls'])
    newcomb_rls[index][name] = value;
    changeValue('comb_rls', JSON.stringify(newcomb_rls))
  }

  const changefilte_conditionValue = (name, value, index) => {
    let newfilte_condition = stepsArr[stepsCurrent]['filte_condition'] == '' ? [] : JSON.parse(stepsArr[stepsCurrent]['filte_condition'])
    newfilte_condition[index][name] = value;
    changeValue('filte_condition', JSON.stringify(newfilte_condition))
  }
  const changeSUBDATAValue = (name, value, index) => {
    let newstepsArr = stepsArr.concat([])
    newstepsArr[stepsCurrent]['SUB_DATA'][0]['DATA'][index][name] = value;
    console.log('setstepsArr 位置5')
    setstepsArr(newstepsArr)
  }
  const getFields = (index) => {
    setTimeout(() => {
      let indexNow = index || stepsCurrent;
      Dynamic.getDynamicQuery({
        apiID: 'DMT_0003_02',
        'apiParam': {
          "table_name": stepsArr[indexNow]['table_name'],
          "schema": schemaValue
        }
      }).then((res) => {
        console.log('============')
        console.log(res);
        let data = res?.data?.data || []
        // setfieldlist(data)
        changeValue('fields', data);
        let newstepsArr = stepsArr.concat([])
        newstepsArr[indexNow]['SUB_DATA'][0]['DATA'] = [];
        if (!index) {
          data.map((e, i) => {
            newstepsArr[indexNow]['SUB_DATA'][0]['DATA'].push({
              "tgt_column": e["column_name"],
              "data_type": e['data_type'],
              "db_source": "",
              "db_schema": "",
              "table_name": "",
              "src_column": "",
              "rule_id": "",
              "rule_param": ""
            });
          })
        }
        console.log('setstepsArr 位置6')
        setstepsArr(newstepsArr)
      })
    }, 200);

  }
  return <Modal
    title={id === '' ? "新增" : '编辑'}
    visible={isModalVisible}
    onOk={handleOk}
    onCancel={handleCancel}
    centered={true}
    width={1400}
    maskClosable={false}
    bodyStyle={{
      maxHeight: window.innerHeight - 150,
      minHeight: 500,
      height: window.innerHeight - 400,
      overflow: 'auto'
    }}
  >
    <Spin spinning={isloading}>
      <Form form={form} className="dataIntegrationWrap" {...modalLayoutLg}>
        <Row className='dataIntegrationWrapMain'>
          <Col span={5} offset={1}>
            <Form.Item labelCol={{ span: 12 }} wrapperCol={{ span: 12 }} rules={[{ required: true, message: '请输入规则名称' }]} label='规则名称' name='task_name' extra="">
              <Input />
            </Form.Item>
          </Col>
          
          <Col span={4}>
            <Form.Item labelCol={{ span: 12 }} wrapperCol={{ span: 12 }} rules={[{ required: true, message: '请选择目标数据源' }]} label='目标数据源' name='schema' extra="">
              <Select allowClear>
                {databaselist.map((item, index) => (
                  <Option value={item['value']}>{item['label']}</Option>
                ))}
              </Select>
            </Form.Item>
          </Col>
          <Col span={4}>

            <Form.Item labelCol={{ span: 12 }} wrapperCol={{ span: 12 }} label='脚本类型' rules={[{ required: true, message: '请选择脚本类型' }]} name='script_type' extra="">
              {/* <Select>
              <Option value='SQL'>SQL</Option>
              <Option value='Java'>Java</Option>
              <Option value='Python'>Python</Option>
              <Option value='Go'>Go</Option>
            </Select> */}
              <DefineSelect {
                ...{
                  "api_id": "DICT_0001_01",
                  "key_label": "label",
                  "key_value": "value",
                  "param": { "dict_key": "data_gov_script" },
                }
              } />
            </Form.Item>
          </Col>
          <Col span={3}>

            <Form.Item labelCol={{ span: 12 }} wrapperCol={{ span: 12 }} rules={[{ required: true, message: '请选择调度规则' }]} label='调度规则' name='sch_type' extra="">
              <Select defaultValue={'2'}>
                <Option value='1'>定时</Option>
                <Option value='2'>单次</Option>
              </Select>
            </Form.Item>
          </Col>
          {
            sch_typeValue == 1 && <Col span={4}>
              <Form.Item label="调度参数" name='sch_param' extra="">
                <Input />
              </Form.Item>
            </Col>
          }
          <Col span={22} offset={1}>
            <div className='stepWrap'>
              {
                stepsArr.map((e, i) => {
                  return <>
                    <div className='step'>
                      <Button onClick={() => setstepsCurrent(i)} type={stepsCurrent == i ? "primary" : 'default'}>步骤{i + 1}</Button>

                    </div>
                    {
                      i != stepsArr.length - 1 && <div className='rightIcon'>
                        <ArrowRightOutlined style={{ fontSize: '18px' }} />
                      </div>
                    }

                  </>
                })
              }
              <div className='rightIcon' onClick={() => {
                let newstepsArr = stepsArr.concat([])
                newstepsArr.push({
                  // "step_sno": 2,
                  "db_schema": schemaValue,//数据源
                  "table_name": "",//原表
                  "cmd_type": "",//???
                  "step_script": "",//脚本
                  "comb_rls": "",//关联关系
                  "filte_condition": "",//过滤条件
                  "SUB_DATA": [{
                    "API_ID": "DMT_A004_01",
                    "DATA": []
                  }]
                })
                console.log('setstepsArr 位置7')
                setstepsArr(newstepsArr)
              }}>
                <PlusOutlined style={{ fontSize: '18px' }} />
              </div>
            </div>
          </Col>
        </Row>
        {
          schemaValue && scriptYypeValue && <div className='dataIntegrationWrapContent'>

            {
              stepsCurrent != -1 && <div style={{ paddingTop: '15px' }}>
                {
                  scriptYypeValue == 1 && <div>
                    <Row>
                      <Col span={10}>
                        <Form.Item label='脚本类型' onClick={() => {
                          setchangeFlag(true);
                        }}>
                          {/* const [changeFlag,setchangeFlag] = useState(false); */}
                          <DefineSelect
                            value={stepsArr[stepsCurrent]['cmd_type']}
                            onChange={(val) => {

                              changeValue('cmd_type', val)
                              if (changeFlag) {
                                stepsArr[stepsCurrent]['filte_condition'] = '';
                                stepsArr[stepsCurrent]['comb_rls'] = '';
                              }
                              setchangeFlag(false);
                            }}
                            {

                            ...{
                              "api_id": "DICT_0001_01",
                              "key_label": "label",
                              "key_value": "value",
                              "param": { "dict_key": "sql_operation" },
                            }
                            } />
                        </Form.Item>

                      </Col>
                      <Col span={8}>
                        <Form.Item label='目标表'>
                          <DefineSelect
                            value={stepsArr[stepsCurrent]['table_name']}
                            onChange={(val) => {
                              changeValue('table_name', val)
                              getFields();
                            }}
                            {

                            ...{
                              "api_id": "DMT_0003",
                              "key_label": "tablename",
                              "key_value": "tablename",
                              "param": { "schema": schemaValue },
                            }
                            } />
                        </Form.Item>
                      </Col>
                    </Row>
                    {
                      ['INS', 'UPD'].indexOf(stepsArr[stepsCurrent]['cmd_type']) != -1 && <Row>
                        <Col span={23} offset={1}>
                          <Table rowSelection={{
                            selectedRowKeys: stepsArr[stepsCurrent]['checked'],
                            onChange: (newSelectedRowKeys) => {
                              console.log(newSelectedRowKeys)
                              changeValue('checked', newSelectedRowKeys)
                            }
                          }} columns={columns} rowKey="column_name" dataSource={stepsArr[stepsCurrent]['fields']} pagination={false} scroll={{ x: "max-content" }} />
                        </Col>
                      </Row>
                    }
                    {
                      ['INS', 'UPD', 'DLT'].indexOf(stepsArr[stepsCurrent]['cmd_type']) != -1 && <Row>
                        <Col span={23} offset={1}>
                          {
                            stepsArr[stepsCurrent]['cmd_type'] != 'DLT' && <div className='otheritem' style={{ marginTop: '10px' }}>

                              <Form.Item colon={false} label={
                                <div>
                                  <div>关联关系</div>
                                  <Button size={'small'} type="link" onClick={() => {
                                    let newcomb_rls = stepsArr[stepsCurrent]['comb_rls'] == '' ? [] : JSON.parse(stepsArr[stepsCurrent]['comb_rls'])
                                    newcomb_rls.push({
                                      connector: "",//连接符
                                      left_table: "",//左表
                                      jn_type: "",//链接字符
                                      right_table: '',//右表
                                      left_column: '',//左表字段
                                      comparator: '',//比较字段
                                      right_column: '',//右表字段
                                    })
                                    changeValue('comb_rls', JSON.stringify(newcomb_rls))
                                  }}>添加</Button>
                                </div>
                              }
                                labelCol={{ span: 2 }}
                                wrapperCol={{ span: 21, offset: 1 }}
                              >
                                {/* <Input
      value={stepsArr[stepsCurrent]['comb_rls']}
      onChange={(e) => {
        changeValue('comb_rls', e.target.value)
      }}
      {

      ...{
        "api_id": "DMT_0003",
        "key_label": "tablename",
        "key_value": "tablename",
        "param": { "schema": schemaValue },
      }
      } /> */}
                                {
                                  (stepsArr[stepsCurrent]['comb_rls'] == '' ? [] : JSON.parse(stepsArr[stepsCurrent]['comb_rls'])).map((e, i) => {
                                    let DataS = stepsArr?.[stepsCurrent]?.['SUB_DATA']?.[0]['DATA'];
                                  let arr = [];
                                  let schames = [];
                                  let fieldss = [];
                                  let tableschema = {};
                                  DataS.map((e, i) => {
                                    if (arr.indexOf(e.table_name) == -1 && e.table_name != '') {
                                      arr.push(e.table_name);
                                      schames.push(e.db_source)
                                      tableschema[e.table_name] = e.db_schema
                                      fieldss.push(e.column_name);
                                    }
                                  })
                                  if (arr.indexOf(stepsArr[stepsCurrent]['table_name']) == -1) {
                                    arr.push(stepsArr[stepsCurrent]['table_name'])
                                    schames.push(schemaValue);
                                  }

                                    // left_table: "",//左表
                                    // jn_type: "",//链接字符
                                    // right_table: '',//右表
                                    // left_column: '',//左表字段
                                    // comparator: '',//比较字段
                                    // right_column: '',//右表字段
                                    return <div style={{ marginBottom: '10px' }}>
                                      <Form layout="inline">
                                        <div style={{ width: '100px', display: "inline-block" }}>
                                          {
                                            i != 0 && <Form.Item>

                                              <DefineSelectComp
                                                value={e.connector}
                                                placeholder='连接符'
                                                onChange={(val) => {
                                                  changeComb_rlsValue('connector', val, i)
                                                }}

                                                {
                                                ...{
                                                  "api_id": "DICT_0001_01",
                                                  "key_label": "label",
                                                  "key_value": "value",
                                                  "param": { "dict_key": "condition_connector" },
                                                }
                                                } />
                                            </Form.Item>
                                          }
                                        </div>

                                        <Form.Item>
                                          <Select style={{ width: '160px' }} placeholder='左表' value={e.left_table} onChange={(val) => {
                                            changeComb_rlsValue('left_table', val, i)
                                          }}>
                                            {
                                              arr.map((e) => {
                                                return <Option value={e}>{e}</Option>
                                              })
                                            }
                                          </Select>
                                        </Form.Item>
                                        <Form.Item>

                                          <DefineSelectComp
                                            value={e.jn_type} placeholder='链接字符' onChange={(val) => {
                                              changeComb_rlsValue('jn_type', val, i)
                                            }}

                                            {
                                            ...{
                                              "api_id": "DICT_0001_01",
                                              "key_label": "label",
                                              "key_value": "value",
                                              "param": { "dict_key": "table_join" },
                                            }
                                            } />
                                        </Form.Item>
                                        <Form.Item>

                                          <Select style={{ width: '160px' }} value={e.right_table} placeholder="右表" onChange={(val) => {
                                            changeComb_rlsValue('right_table', val, i)
                                          }}>
                                            {
                                              arr.map((e) => {
                                                return <Option value={e}>{e}</Option>
                                              })
                                            }
                                          </Select>
                                        </Form.Item>
                                        <Form.Item>
                                          <span>on</span>
                                        </Form.Item>
                                        <Form.Item>

                                          <DefineSelectComp
                                            value={e.left_column} placeholder="左表字段" onChange={(val) => {
                                              changeComb_rlsValue('left_column', val, i)
                                            }}

                                            {
                                            ...{
                                              "api_id": "DMT_0003_02",
                                              "key_label": "column_name",
                                              "key_value": "column_name",
                                              "param": {
                                                "table_name": e.left_table,
                                                "schema":e.left_table==stepsArr[stepsCurrent]['table_name']?schemaValue:   tableschema[e.left_table]
                                              },
                                            }
                                            } />
                                        </Form.Item>
                                        <Form.Item>

                                          <DefineSelectComp
                                            value={e.comparator} placeholder="比较字段" onChange={(val) => {
                                              changeComb_rlsValue('comparator', val, i)
                                            }}

                                            {
                                            ...{
                                              "api_id": "DICT_0001_01",
                                              "key_label": "label",
                                              "key_value": "value",
                                              "param": { "dict_key": "condition_comparator" },
                                            }
                                            } />
                                        </Form.Item>

                                        <Form.Item>


                                          <DefineSelectComp
                                            value={e.right_column} placeholder="右表字段" onChange={(val) => {
                                              changeComb_rlsValue('right_column', val, i)
                                            }}
                                            {
                                            ...{
                                              "api_id": "DMT_0003_02",
                                              "key_label": "column_name",
                                              "key_value": "column_name",
                                              "param": {
                                                "table_name": e.right_table,
                                                // "schema": tableschema[e.right_table]
                                                "schema":e.right_table==stepsArr[stepsCurrent]['table_name']?schemaValue:   tableschema[e.right_table]
                                              },
                                            }
                                            } />
                                        </Form.Item>
                                        {/* {
            i!=0&& <Form.Item>
            <a onClick={()=>{
              let newcomb_rls = stepsArr[stepsCurrent]['comb_rls'] == '' ? [] : JSON.parse(stepsArr[stepsCurrent]['comb_rls'])
              newcomb_rls.splice(i,1)
              changeValue('comb_rls', JSON.stringify(newcomb_rls))
            }}>删除</a>
          </Form.Item>
          } */}
                                        <Form.Item>
                                          <a onClick={() => {
                                            let newcomb_rls = stepsArr[stepsCurrent]['comb_rls'] == '' ? [] : JSON.parse(stepsArr[stepsCurrent]['comb_rls'])
                                            newcomb_rls.splice(i, 1)
                                            changeValue('comb_rls', JSON.stringify(newcomb_rls))
                                          }}>删除</a>
                                        </Form.Item>
                                      </Form>







                                    </div>
                                  })
                                }


                              </Form.Item>
                            </div>
                          }

                          <div className='otheritem' style={{ marginTop: '10px' }}>
                            <Form.Item colon={false} label={
                              <div>
                                <div>过滤条件</div>
                                <Button size={'small'} type="link" onClick={() => {
                                  let newfilte_condition = stepsArr[stepsCurrent]['filte_condition'] == '' ? [] : JSON.parse(stepsArr[stepsCurrent]['filte_condition'])
                                  newfilte_condition.push({
                                    connector: '',//连接符
                                    table_name: '',//表名
                                    column_name: '',//字段
                                    right_table: '',//右表
                                    comparator: '',//比较符
                                    com_param: '',//参数
                                    type: '1',//1-参数  2-right_table   right_column
                                    right_column: ''
                                  })
                                  changeValue('filte_condition', JSON.stringify(newfilte_condition))
                                }}>添加</Button>
                              </div>
                            }
                            labelCol={{ span: 2 }}
                            wrapperCol={{ span: 21, offset: 1 }}
                            >
                              {/* <Input
      value={stepsArr[stepsCurrent]['filte_condition']}
      onChange={(e) => {
        changeValue('filte_condition', e.target.value)
      }}
      {

      ...{
        "api_id": "DICT_0001_01",
        "key_label": "label",
        "key_value": "value",
        "param": { "dict_key": "sql_operation" },
      }
      } /> */}
                              {
                                (stepsArr[stepsCurrent]['filte_condition'] == '' ? [] : JSON.parse(stepsArr[stepsCurrent]['filte_condition'])).map((e, i) => {
                                  let DataS = stepsArr?.[stepsCurrent]?.['SUB_DATA']?.[0]['DATA'];
                                  let arr = [];
                                  let schames = [];
                                  let fieldss = [];
                                  let tableschema = {};
                                  DataS.map((e, i) => {
                                    if (arr.indexOf(e.table_name) == -1 && e.table_name != '') {
                                      arr.push(e.table_name);
                                      schames.push(e.db_source)
                                      tableschema[e.table_name] = e.db_schema
                                      fieldss.push(e.column_name);
                                    }
                                  })
                                  if (arr.indexOf(stepsArr[stepsCurrent]['table_name']) == -1) {
                                    arr.push(stepsArr[stepsCurrent]['table_name'])
                                    schames.push(schemaValue);
                                  }
                                  return <div style={{ marginBottom: '10px' }}>
                                    <Form layout="inline">
                                      <div style={{ width: '100px', display: "inline-block" }}>
                                        {
                                          i != 0 && <Form.Item>

                                            <DefineSelectComp
                                              placeholder="连接符"
                                              value={e.connector} onChange={(val) => {
                                                changefilte_conditionValue('connector', val, i)
                                              }}

                                              {
                                              ...{
                                                "api_id": "DICT_0001_01",
                                                "key_label": "label",
                                                "key_value": "value",
                                                "param": { "dict_key": "condition_connector" },
                                              }
                                              } />
                                          </Form.Item>
                                        }
                                      </div>
                                      <Form.Item>
                                        {
                                          stepsArr[stepsCurrent]['cmd_type'] == 'DLT' ? <span>{stepsArr[stepsCurrent]['table_name']}</span> : <Select style={{ width: '160px' }}placeholder="表名" value={e.table_name} onChange={(val) => {
                                            changefilte_conditionValue('table_name', val, i)
                                          }}>
                                            {
                                              arr.map((e) => {
                                                return <Option value={e}>{e}</Option>
                                              })
                                            }
                                          </Select>
                                        }

                                      </Form.Item>

                                      <Form.Item>

                                        <DefineSelectComp
                                          value={e.column_name} placeholder="字段" onChange={(val) => {
                                            changefilte_conditionValue('column_name', val, i)
                                          }}

                                          {
                                          ...{
                                            "api_id": "DMT_0003_02",
                                            "key_label": "column_name",
                                            "key_value": "column_name",
                                            "param": {
                                              "table_name": stepsArr[stepsCurrent]['cmd_type'] == 'DLT' ? stepsArr[stepsCurrent]['table_name'] : e.table_name,
                                              "schema": (stepsArr[stepsCurrent]['cmd_type'] == 'DLT' ||e.table_name==stepsArr[stepsCurrent]['table_name'])? schemaValue : tableschema[e.table_name]
                                            },
                                          }
                                          } />
                                      </Form.Item>
                                      <Form.Item>

                                        <DefineSelectComp
                                          value={e.comparator} placeholder="比较符" onChange={(val) => {
                                            changefilte_conditionValue('comparator', val, i)
                                          }}

                                          {
                                          ...{
                                            "api_id": "DICT_0001_01",
                                            "key_label": "label",
                                            "key_value": "value",
                                            "param": { "dict_key": "condition_comparator" },
                                          }
                                          } />
                                      </Form.Item>
                                      {
                                        stepsArr[stepsCurrent]['cmd_type'] != 'DLT'&&<Form.Item>
                                        <Select style={{ width: '160px' }} placeholder="类型" value={e.type} onChange={(val) => {
                                          changefilte_conditionValue('type', val, i)
                                        }}>
                                          <Option value={'1'}>参数</Option>
                                          <Option value={'2'}>表</Option>
                                        </Select>
                                      </Form.Item>
                                      }
                                      
                                      {
                                        e.type == '1' && <Form.Item>
                                          <Input

                                            value={e.com_param} placeholder="com_param" onChange={(e) => {
                                              changefilte_conditionValue('com_param', e.target.value, i)
                                            }}
                                          />
                                        </Form.Item>
                                      }
                                      {
                                        e.type == '2' && <>
                                          <Form.Item>

                                            <Select style={{ width: '160px' }} value={e.right_table} placeholder="右表" onChange={(val) => {
                                              changefilte_conditionValue('right_table', val, i)
                                            }}>
                                              {
                                                arr.map((e) => {
                                                  return <Option value={e}>{e}</Option>
                                                })
                                              }
                                            </Select>
                                          </Form.Item>
                                          <Form.Item>


                                            <DefineSelectComp
                                              value={e.right_column} placeholder="右表字段" onChange={(val) => {
                                                changefilte_conditionValue('right_column', val, i)
                                              }}
                                              {
                                              ...{
                                                "api_id": "DMT_0003_02",
                                                "key_label": "column_name",
                                                "key_value": "column_name",
                                                "param": {
                                                  "table_name": e.right_table,
                                                  "schema": e.right_table==stepsArr[stepsCurrent]['table_name']?schemaValue: tableschema[e.right_table]
                                                },
                                              }
                                              } />
                                          </Form.Item>
                                        </>
                                      }
                                      {/* {
            i!=0&& <Form.Item>
            <a onClick={()=>{
              let newfilte_condition = stepsArr[stepsCurrent]['filte_condition'] == '' ? [] : JSON.parse(stepsArr[stepsCurrent]['filte_condition'])
              newfilte_condition.splice(i,1);
              changeValue('filte_condition', JSON.stringify(newfilte_condition))
            }}>删除</a>
          </Form.Item>
          } */}
                                      <Form.Item>
                                        <a onClick={() => {
                                          let newfilte_condition = stepsArr[stepsCurrent]['filte_condition'] == '' ? [] : JSON.parse(stepsArr[stepsCurrent]['filte_condition'])
                                          newfilte_condition.splice(i, 1);
                                          changeValue('filte_condition', JSON.stringify(newfilte_condition))
                                        }}>删除</a>
                                      </Form.Item>
                                    </Form>

                                  </div>
                                })
                              }

                            </Form.Item>
                          </div>
                        </Col>
                      </Row>
                    }
                    {
                      stepsArr[stepsCurrent]['cmd_type'] == 'SCT' && <div>
                        <Row>
                          <Col span={23} offset={1}>
                            <Input.TextArea value={stepsArr[stepsCurrent]['step_script']}
                              onChange={(e) => {
                                changeValue('step_script', e.target.value)
                              }} rows={8} />
                          </Col>
                        </Row>

                      </div>
                    }

                  </div>
                }
                {
                  scriptYypeValue != 1 && <div>
                    <Row>
                      <Col span={23} offset={1}>
                        <Input.TextArea value={stepsArr[stepsCurrent]['step_script']}
                          onChange={(e) => {
                            changeValue('step_script', e.target.value)
                          }} name="" rows={8} />
                      </Col>
                    </Row>

                  </div>
                }
              </div>
            }

          </div>
        }


      </Form>
    </Spin>

  </Modal>
}
const AddMCom = forwardRef(AddM);



const LogM = (props, refs) => {
  const [isModalVisible, setIsModalVisible] = useState(false);
  const [id, setid] = useState('');
  const [logVisible, setlogVisible] = useState(false);
  const [log, setlog] = useState('');
  const [loading, setloading] = useState(false);
  // const [isLoading,setisLoading ] = useState(false);
  const showModal = () => {
    setIsModalVisible(true);
  };
  const handleCancel = () => {
    setIsModalVisible(false);
    props.callback && props.callback();
  };
  useImperativeHandle(refs, () => ({
    init: (id) => {
      showModal();
      setid(id)
      // setfileList([]);
      //showModal();
      getDetail(id);
    }
  }))
  const getDetail = (id) => {
    setloading(true);
    Dynamic.getDynamicQuery({
      apiID: 'DMT_B002_03',
      apiParam: {
        logID: id
      }
    }).then((res) => {
      console.log(res);
      let data = res?.data?.data[0];
      let html = data?.run_log.replaceAll('\n', '<br />')
      setlog(html)
      setloading(false);

    })
  }
  return <Modal
    title={'测试结果'}
    visible={isModalVisible}
    onCancel={handleCancel}
    centered={true}
    width={580}
    destroyOnClose={true}
    maskClosable={false}
    className="dataTemModal"
    bodyStyle={{
      maxHeight: window.innerHeight - 160,
      overflow: "auto"
    }}
    footer={
      <Button onClick={handleCancel}>关闭</Button>
    }
  >
    {
      loading ? <div className='example'><Spin /></div> : <div>
        {
          log.split('<br />').map((e, i) => {
            return <div key={i}>{e}</div>
          })
        }
      </div>
    }

    {/* {log} */}
  </Modal>
}

const LogMCom = forwardRef(LogM);